﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace GotLyrics.LyricGrabbers
{
    /// <summary>
    /// This is the lyric grabber for LyrDB.com
    /// </summary>
    public class LyrDBGrabber : LyricGrabber
    {
        // public LyrDBGrabber() { Enabled = false; }

        /// <summary>
        /// The website of this lyrics provider. This is pointing to the main page on the website.
        /// </summary>
        /// <value></value>
        public override string WebSiteUrl
        {
            get { return "http://www.lyrdb.com/"; }
        }

        private string GetRequestAddress(LyricGrabberContext context)
        {
            string artist = context.Tags.Artist;
            string title = context.Tags.Title;

            return string.Format("http://webservices.lyrdb.com/lookup.php?q={0}|{1}&for=match", 
                                 HttpUtility.UrlEncode(artist), 
                                 HttpUtility.UrlEncode(title));
        }

        private string ParseResponse(LyricGrabberContext context, string response)
        {
            string[] lines = response.Split('\n');

            foreach (string line in lines)
            {
                string id = line.Split('\\')[0];

                string request = "http://webservices.lyrdb.com/getlyr.php?q=" + id;

                string lyrics = WebClient.DownloadString(request);

                if(!string.IsNullOrEmpty(lyrics) &&
                   !lyrics.StartsWith("error:"))
                    return lyrics.Trim(" \t\r\n".ToCharArray());
            }

            return null;
        }

        /// <summary>
        /// Grabs the lyric based on the current <see cref="Context"/> from the webservice.
        /// </summary>
        /// <param name="context"></param>
        /// <returns>
        /// The lyric if one was found, otherwise <c>null</c>.
        /// </returns>
        protected override string GrabLyric(LyricGrabberContext context)
        {
            string url = GetRequestAddress(context);
            string response = WebClient.DownloadString(url);
            string lyrics = ParseResponse(context, response);

            return lyrics;
        }
    }
}
